package com.zcxx.cotton.base;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.zcxx.cotton.base.domain.PubPickerDevice;
import com.zcxx.cotton.base.service.IPubPickerDeviceService;
import com.zcxx.cotton.pick.domain.PickInfo;
import com.zcxx.cotton.pick.domain.PickMapElement;
import com.zcxx.cotton.pick.service.IPickInfoService;
import com.zcxx.cotton.pick.service.IPickMapElementService;
import com.zcxx.cotton.pick.util.MapUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.ruoyi.common.utils.PageUtils.startPage;

/**
 * @author 吴璇璇
 * @title: StatisticsController
 * @projectName ruoyi
 * @description: TODO
 * @date 2025/8/1 10:32
 */

@RestController
@RequestMapping("/statistics")
public class StatisticsController extends BaseController {

    @Autowired
    private IPubPickerDeviceService pubPickerDeviceService;

    @Autowired
    private IPickInfoService pickInfoService;

    @Autowired
    private IPickMapElementService pickMapElementService;

    /**
     * 基本信息-查询四个数量
     */
    @ApiOperation("统计信息")
    @PostMapping("/getCount")
    public Map<String, Object> getPickerDeviceCount() {
        Map<String,Object> map=new HashMap<>();
        //棉机数量
        List<PubPickerDevice> list = pubPickerDeviceService.list();
        map.put("deviceCount",list.size());
        //棉机在线数量
        LambdaQueryWrapper<PubPickerDevice>queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(PubPickerDevice::getStatus,"0");
        List<PubPickerDevice> listOnline = pubPickerDeviceService.list(queryWrapper);
        map.put("deviceOnlineCount",listOnline.size());
        //采摘棉包总数
        List<PickInfo> pickInfos = pickInfoService.selectPickInfoList(null);
        map.put("pickCount",pickInfos.size());
        //今日采摘数(个)
        PickInfo pickInfo=new PickInfo();
        pickInfo.setBeginBillDate(DateUtils.getDate()+" 00:00:00");
        pickInfo.setEndBillDate(DateUtils.getDate()+" 23:59:59");
        List<PickInfo> pickInfoToday = pickInfoService.selectPickInfoList(pickInfo);
        map.put("pickTodayCount",pickInfoToday.size());
        //采棉总面积：
        //使用所有的棉包数量*4.5（乘积）和所有区的面积对比，如果乘积>=所有区的面积和，则采棉总面积显示所有区的面积和，如果乘积<所有区的面积和,则采棉总面积显示乘积。
        List<PickInfo> pickInfoList = pickInfoService.list();
        long count = pickInfoList.size();
        double area = count * 4.5;

        List<PickMapElement> pickMapElements = pickMapElementService.selectAll("pick_map_element_1084",null);
        double areaSum = 0;
        if (pickMapElements != null && !pickMapElements.isEmpty()) {
            areaSum = pickMapElements.stream()
                    .filter(Objects::nonNull) // 过滤掉null元素
                    .mapToDouble(element -> {
                        Double areaValue = element.getArea();
                        return areaValue != null ? areaValue : 0.0; // 处理getArea()返回null的情况
                    })
                    .sum();
        }

        map.put("pickArea", Math.min(area, areaSum));
        //今日采摘总面积：
        //按照今日棉包落的片区确定，每个片区单独计算处理，仍使用棉包数量*4.5（乘积）与当前片区的面积对比，乘积>=当前片区面积，则今日采摘面积显示当前区的面积，如果乘积<当前片区面积,则今日采摘总面积显示乘积。

        //筛选今日棉包 createTime >= 今日0点，createTime < 今日23:59:59
      /*  List<PickInfo> pickInfoTodayList = pickInfoList.stream().filter(info ->
                DateUtils.differentDaysByMillisecond(
                        DateUtils.parseDate(info.getCreateTime()),
                        DateUtils.parseDate(DateUtils.getDate())) == 0).collect(Collectors.toList());*/

        double areaToday = 0;
        if (pickMapElements != null) {
            for (PickMapElement pickMapElement : pickMapElements) {
                // 筛选属于该片区的棉包
                //List<PickInfo> pickInfoListByElement = pickInfoTodayList.stream().filter(info -> MapUtil.isPointInPolygon(Double.parseDouble(info.getLatitude()), Double.parseDouble(info.getLongitude()), pickMapElement.getLatlng())).collect(Collectors.toList());
                List<PickInfo> pickInfoListByElement = pickInfoToday.stream().filter(x -> x.getId().equals(pickMapElement.getId())).collect(Collectors.toList());
                double areaTodayByElement = pickInfoListByElement.size() * 4.5;
                // 获取最小面积
                areaToday += Math.min(areaTodayByElement, pickMapElement.getArea());
            }
        }
        map.put("pickAreaToday", areaToday);

        return AjaxResult.success(map);
    }




    /**
     * 查询当前农业公司的统计信息
     */
    @ApiOperation("统计信息")
    @PostMapping("/getCountByCategory")
    public Map<String, Object> getCountByCategory(String category) {
        Map<String, Object> map = new HashMap<>();
        //当前农业公司棉包总数(个)
        BigDecimal mianbaoZong=pickInfoService.selectMianbaoTotal(category);
        map.put("mianbaoZong",mianbaoZong);
        //当前农业公司今日采摘数(个)
        BigDecimal mianbaoToday=pickInfoService.selectMianbaoToday(category);
        map.put("mianbaoToday",mianbaoToday);
        //当前农业公司总采收面积（亩）
        //使用当前农业公司的棉包数量*4.5（乘积）和当前农业公司所有区的面积对比，如果乘积>=所有区的面积和，则采棉总面积显示所有区的面积和，如果乘积<所有区的面积和,则采棉总面积显示乘积。
        // 正确方式 - 使用字符串避免精度问题
        BigDecimal multiplier = new BigDecimal("4.5");
        BigDecimal area = mianbaoZong.multiply(multiplier);
        //查询当前农业公司所有区的面积
        BigDecimal area1=pickMapElementService.selectTotalArea(category);
        BigDecimal totalArea = area.compareTo(area1) < 0 ? area : area1;
        map.put("ZongArea", totalArea);

        //今日采摘总面积：
        //按照今日棉包落的片区确定，每个片区单独计算处理，仍使用棉包数量*4.5（乘积）与当前片区的面积对比，乘积>=当前片区面积，则今日采摘面积显示当前区的面积，如果乘积<当前片区面积,则今日采摘总面积显示乘积。
        //查询当前农业公司今日的面包
        List<PickInfo> todayList=pickInfoService.selectTodayBao(category);
        //当前农业公司所有的地块
        List<PickMapElement> pickMapElements = pickMapElementService.selectAll("pick_map_element_1084",category);
        double areaToday = 0;
        if (pickMapElements != null) {
            for (PickMapElement pickMapElement : pickMapElements) {
                // 筛选属于该片区的棉包
                List<PickInfo> pickInfos = todayList.stream().filter(x -> x.getId().equals(pickMapElement.getId())).collect(Collectors.toList());
                double areaTodayByElement = pickInfos.size() * 4.5;
                // 获取最小面积
                areaToday += Math.min(areaTodayByElement, pickMapElement.getArea());
            }
        }
        map.put("TodayArea", areaToday);
        return AjaxResult.success(map);
    }



    /**
     * 查询采摘信息列表
     */
    @GetMapping("/selectReportList")
    public TableDataInfo selectReportList(PickInfo pickInfo){
        startPage();
        List<PickInfo> list = pickInfoService.selectReportList(pickInfo);
        return getDataTable(list);
    }


}
